package com.etlmaster.executor.steps.datax;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.dp.nebula.wormhole.plugins.common.DBSource;
import com.etlmaster.datax.engine.core.Engine;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.LogWriter;
import com.etlmaster.executor.utils.StepState;

import freemarker.core.FreeMarkerTemplate;

/**
 * @author Wugf
 * @date 2016-03-08
 */
public class DataxWriter {
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	public static Map<String,String> runDatax(int hashCode,String pluginName,String readerPluginConf,Map<String,String> data){
		int flag=StepState.RUNNING_SUCCESSED;
		String db2Writer=FreeMarkerTemplate.getFpl(pluginName, data);
		Map<String,String> rtnFlag=new HashMap<String,String>();
		if(db2Writer==null){
			LogWriter.addLog("ERROR","生成Write配置失败!");
			rtnFlag.put("status", StepState.RUNNING_FAILED+"");
			return rtnFlag;
		}else{
			LogWriter.addLog("INFO","生成writer配置成功");
		}
		try {
			File f = null;
			
			String logPath = DpExecutorUtils.getLogPath()+"/";
			LogWriter.addLog("DEBUG",logPath);
			f = DpExecutorUtils.writeToFile(db2Writer.toString(), "xml", logPath,hashCode);
			
		} catch (IOException e) {
			flag = StepState.RUNNING_FAILED;
			LogWriter.addLog("ERROR",e.getMessage());
			LogWriter.addLog("ERROR","生成配置文件错误");
		}
		try {
			File f = null;
			
			String logPath = DpExecutorUtils.getLogPath()+"/";
			f = DpExecutorUtils.writeToFile(db2Writer.toString(), "xml", logPath,hashCode);
			String writerPluginConf=f.getPath();
			
			if(readerPluginConf==null){
				flag=StepState.RUNNING_FAILED;
			}else{
			
			String jobXmlFile=DpExecutorUtils.writeJobConfig(readerPluginConf, writerPluginConf, logPath, "xml",hashCode);
			
			rtnFlag=new Engine().runJob(jobXmlFile);;
			if(rtnFlag.get("status").equals("0")){
				
				
			}else{
				LogWriter.addLog("ERROR","数据交换失败！返回值为：{}", rtnFlag+"");
				flag = StepState.RUNNING_FAILED;
			}
			}
		} catch (Exception e) {
			flag = StepState.RUNNING_FAILED;
			LogWriter.addLog("ERROR","生成配置文件错误");
			
			
		}
		DBSource.sourceInfoMap.clear();
		return rtnFlag;
	}

}
